from PyQt5.QtCore import QVariant, QAbstractListModel,QAbstractTableModel,pyqtProperty, Qt, QObject, pyqtSlot, pyqtSignal
from PyQt5.QtQml import  QQmlComponent
from PyQt5.QtCore import QTimer, QUrl
from PyQt5 import QtCore,QtWidgets
from time import strftime, localtime
import logging
import pandas
import json
import traceback
import os
import datetime
# from bpptablemodel import BTModel
class Bridge(QObject):
    
    updated = pyqtSignal(str, arguments=['time'])
    columnsChanged= pyqtSignal(QVariant)
    modelChanged=pyqtSignal(QObject)
    def __init__(self,parent=None):
        super().__init__(parent)
        self.export_num=0
        n=datetime.datetime.now().year % 2000
        n0=n-1
        n=str(n)
        n0=str(n0)
        self.sample_name_pattern="(%s|%s)[A-Z][A-Z][0-9]*-[1-9]" % (n,n0)
        self.db = None
        # myglobal.bridge = self
        # self.timer = QTimer()
        # self.timer.setInterval(1000)  # msecs 100 = 1/10th sec
        # self.timer.timeout.connect(self.update_time)
        # self.timer.start()
        self._model = BTModel()
        self._model2 = BTModel()
        self.set_database()
        # self.demo()
    @pyqtSlot()
    def demo(self):
        self._model.demo()
        self.columnsChanged.emit(self._model.props)
        self.modelChanged.emit(self._model)
    @pyqtSlot(int,bool)
    def column_visible(self,column,visible):
        logging.info([column,visible])
        col=column #self.model.visColToCol(column)
        self.model.properties[col]["visible"]=visible
        self.model2.properties[col]["visible"]=visible
        self.model.visProps= list(filter(lambda x: x["visible"]== True, self.model.properties))
        self.model2.visProps= list(filter(lambda x: x["visible"]== True,self.model2.properties))
        self._model.updateLayout()
        self._model2.updateLayout()
        self.columnsChanged.emit(self._model.properties)
        # self.modelChanged.emit()
        # self.model2Changed.emit()
        pass
    def addObject():
        qml = b'''
        import People 1.0

        CheckBox {
            name: "Bob Jones"
            shoeSize: 12
        }
        '''
        component = QQmlComponent(engine)
        component.setData(qml, QUrl())

        person = component.create()

        if person is not None:
            print("The person's name is \"%s\"" % person.name)
            print("They wear a %d sized shoe" % person.shoeSize)
        else:
            print("Unable to create component instance")
            for e in component.errors():
                print("Error:", e.toString());
    sblx_indexChanged=pyqtSignal(int)
    @pyqtProperty(str, notify=sblx_indexChanged)
    def sblx(self):
        at= config_json.setting["sblx_index"]
        if at is None:
            at=0
        return config_json.setting["sblx_list"][at]

    
    @pyqtProperty(int, notify=sblx_indexChanged)
    def sblx_index(self):
        # logging.info(config_json.setting)
        return config_json.setting["sblx_index"]

    @sblx_index.setter
    def sblx_index(self, shoeSize):
        logging.info("set")
        config_json.setting["sblx_index"] = shoeSize
        self.sblx_indexChanged.emit(shoeSize)
        self.set_database()

    outputChanged=pyqtSignal()
    @pyqtProperty(str, notify=outputChanged)
    def output(self):
        # logging.info(config_json.setting)
        return config_json.setting["output_folder"]

    @output.setter
    def output(self, shoeSize):
        logging.info("set")
        config_json.setting["output_folder"] = shoeSize

    inputChanged = pyqtSignal()

    @pyqtProperty(str, notify=inputChanged)
    def input(self):
        # logging.info(config_json.setting)
        return config_json.setting["database"]

    @input.setter
    def input(self, shoeSize):
        config_json.setting["database"] = shoeSize

    def set_database(self):
        return
        # self.ui.groupBox_images.setVisible(False)
        at=config_json.setting["sblx_index"]
        if at is None:
            at=0
        logging.info(at)
        sblx=config_json.setting["sblx_list"][at]
        logging.info(sblx)
        if sblx in ["ajl_pdf", "6300", "icap"]:  # icp
            from icp import MyDb
            self.appends = config_json.setting["append"].get("icp", {})
            self.db = MyDb(self)
        elif sblx in ["spec", "4460"]:  # spec
            self.appends = config_json.setting["append"].get("spec", {})
            self.db = spectro.MyDb(self)
        elif sblx == "weight":
            self.appends = config_json.setting["append"].get("weight", {})
            self.db = weight.MyDb(self)
        elif sblx == "diding":
            self.appends = config_json.setting["append"].get("diding", {})
            self.db = diding.MyDb(self)
        elif sblx == "guangdu":
            self.appends = config_json.setting["append"].get("guangdu", {})
            self.db = guangdu.MyDb(self)
        elif sblx == "zwk":
            self.appends = config_json.setting["append"].get("zwk", {})
            self.db = zwk.MyDb(self)
        elif sblx in ["ajl8900", "icap_q", "ncs300"]:  # icpms
            from icpms import MyDb
            self.appends = config_json.setting["append"].get("icpms", {})
            self.db = MyDb(self)
        else:  # csonh
            self.appends = config_json.setting["append"].get("csonh", {})
            self.db = csonh.MyDb(self)
        logging.info(self.appends)

    @pyqtSlot()
    def up(self):
        # n = self._model2.rowCount()
        objs=[]
        for i in self._model2.highlightRows._data:
            obj = self._model2._data.iloc[i]
            objs.append(obj)
        self._model.beginResetModel()
        self._model2.beginResetModel()
        for obj in objs:
            self._model._data.loc[obj.name]=obj
            self._model2._data=self._model2._data.drop(obj.name)
        self._model._data=self.model._data.sort_values("num", ascending=True)
        self._model2.endResetModel()
        self._model.endResetModel()

    @pyqtSlot()
    def down(self):
        objs=[]
        for i in self._model.highlightRows._data:
            obj = self._model._data.iloc[i]
            objs.append(obj)
        self._model.beginResetModel()
        self._model2.beginResetModel()
        for obj in objs:
            self._model2._data.loc[obj.name]=obj
            self._model._data=self._model._data.drop(obj.name)
        self._model2._data=self.model2._data.sort_values("num", ascending=True)
        self._model2.endResetModel()
        self._model.endResetModel()
        # self._model.dataChanged.emit(self._model.index(minRow, 0), self._model.index(maxRow, len(self.properties) - 1), [Qt.UserRole]);
        # self.modelChanged.emit()
        # self.model2Changed.emit()

        # self._model.highlightRows
        # n = self._model.rowCount()
        # objs=[]
        # for i in range(n):
        #     obj = self._model._data.iloc[i]
        #     if obj["check"]:
        #         objs.append(obj)
        # for obj in objs:
        #     self._model2._data.loc[obj.name]=obj
        #     self._model._data=self._model._data.drop(obj.name)
        # self._model2._data=self.model2._data.sort_values("num", ascending=True)
        # self.modelChanged.emit()
        # self.model2Changed.emit()
    @pyqtSlot()
    def down_all(self):
        n = self._model.rowCount()
        objs=[]
        for i in range(n):
            obj = self._model._data.iloc[i]
            objs.append(obj)
        self._model.beginResetModel()
        self._model2.beginResetModel()
        for obj in objs:
            self._model2._data.loc[obj.name]=obj
            self._model._data=self._model._data.drop(obj.name)
        self._model2._data=self.model2._data.sort_values("num", ascending=True)
        self._model2.endResetModel()
        self._model.endResetModel()
    itemsChanged=pyqtSignal()
    @pyqtSlot()
    def import_last(self):
        self.df = self.db.getDataDays(200)
        self._model.setObjects(self.df, self.db.properties)
        logging.info(self._model._data.columns)
        logging.info(self._model._data)
        logging.info(self._model.properties)
        self.df2=pandas.DataFrame(columns=self._model._data.columns)
        self._model2.setObjects(self.df2, self.db.properties)

        # self.modelChanged.emit()
        # self.model2Changed.emit()
        self.itemsChanged.emit()
        self.columnsChanged.emit(self._model.properties)

    #     self.gen_items()
    
    # def gen_items(self):
    #     self.itemsChanged.emit(self._model.properties)
    @pyqtSlot(str)
    def import_file(self, url):
        logging.info(url)
        # path = QtCore.QUrl(url).toLocalFile()
        config_json.setting["database"] = url
        self.import_last()

    @pyqtSlot(str)
    def lims(self,data):
        data=json.loads(data)
        self.db.lims(data)
    @pyqtSlot(result=str)
    def get_sblx_list(self):
        sblx=config_json.setting["sblx_list"]
        return json.dumps(sblx)
    # @pyqtSlot(result=int)
    # def get_sblx(self):
    #     sblx=sblx
    #     return sblx

    @pyqtSlot()
    def import_click(self):
        at=config_json.setting["sblx_index"]
        if at is None:
            at=0
        sblx=config_json.setting["sblx_list"][at]
        if sblx in ["ncs_cs_db","ncs_onh_db"]:
            self.import_last()
            return
        FileDialog = QtWidgets.QFileDialog(None)
        if config_json.setting["database"]!=None:
            folder = os.path.split(config_json.setting["database"])[0]
            if os.path.exists(folder):
                pass
            else:
                folder=os.path.join(os.path.expanduser('~'), "Desktop")
        else:
            folder=os.path.join(os.path.expanduser('~'), "Desktop")
        if sblx in ["930"]:
            fil = "csv Files (*.csv);;All Files (*)"
        elif sblx == "spec":
            fil = "xlsx Files (*.xlsx);;All Files (*)"
        elif sblx in  ["6300","zwk"]:
            fil = "xls Files (*.xls);;All Files (*)"            
        elif sblx == "ajl_pdf":
            fil = "pdf Files (*.pdf);;All Files (*)"
        elif sblx == "icap":
            fil = "Html Files (*.html);;All Files (*)"
        elif sblx in ["ajl8900"]:
            fil = "xlsx Files (*.xlsx);;All Files (*)"    
        elif sblx in ["leco836_xml","icap_q"]:
            fil = "xml Files (*.xml);;All Files (*)"                
        else:
            fil = "All Files (*)"
        FileDirectory =QtWidgets.QFileDialog.getOpenFileName(
            None, 'select import file', folder, fil)  # 选择目录，返回选中的路径
        # logging.info(FileDirectory)
        fname = FileDirectory[0]
        if fname == "":
            pass
        else:
            try:
                config_json.setting["database"] = fname
                self.import_file(fname)
            except:
                traceback.print_exc() 
    def update_time(self):
        curr_time = strftime("%H:%M:%S", localtime())
        self.updated.emit(curr_time)


if __name__ == '__main__':
    b = Bridge()
    b.getPacks("{}")
